package com.shinhye.elephantsafe;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Application;
import android.os.Environment;

public class ElephantSafeApplication extends Application {
	
	@Override
	public void onCreate() {
		super.onCreate();
		Thread.setDefaultUncaughtExceptionHandler(new MyHandler());
	}
	
	private class MyHandler implements UncaughtExceptionHandler {
		@Override
		public void uncaughtException(Thread thread, Throwable ex) {
			ex.printStackTrace();
			
			if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				String path = Environment.getExternalStorageDirectory().toString() + "/ElephantSafe/error.log";
				File file = new File(path);
				try {
					FileWriter writer = new FileWriter(file, true);
					Date date = new Date();
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					PrintWriter pw = new PrintWriter(writer);
					pw.println("-----------------" + format.format(date) + "-------------------------------------------------------------------------------------");
					ex.printStackTrace(pw);
					pw.println("------------------------------------------------------------------------------------------------------------------------\n");
					pw.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}
	
	@Override
	public void onTerminate() {
		super.onTerminate();
	}
}
